import json

from django.db import transaction
from django.shortcuts import render
from rest_framework.response import Response

# Create your views here.
from rest_framework.viewsets import ModelViewSet
from rest_framework.views import APIView

from Apps.DataGeneration.DataGenerationClass.dataGeneration import DataGenerationEr
from Apps.DataGeneration.filters import DataGenerationCatFilter, DataGenerationFilter
from Apps.DataGeneration.models import DataGeneration, DataGenerationCat
from Apps.DataGeneration.ser import DataGenerationSer, DataGenerationCatSer
from Apps.common.response import SuccessResponse, ErrorResponse

import logging

from Apps.user.models import User
from Apps.util.request_util import setCreateUser, setModifyUser

logger = logging.getLogger("django")


class DataGenerationCatView(ModelViewSet):
    # authentication_classes = []
    queryset = DataGenerationCat.objects.all()
    serializer_class = DataGenerationCatSer
    filter_class = DataGenerationCatFilter

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            logger.info(serializer.data)
            for item in serializer.data:
                item["creator"] = User.objects.get(id=item["creator"]).username
                item["modifier"] = User.objects.get(id=item["modifier"]).username
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)
        return SuccessResponse(serializer.data)

    def create(self, request, *args, **kwargs):
        setCreateUser(request)
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)
        return SuccessResponse("新增成功")

    def update(self, request, *args, **kwargs):
        setModifyUser(request)
        partial = kwargs.pop('partial', False)
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        serializer.is_valid(raise_exception=True)
        self.perform_update(serializer)

        if getattr(instance, '_prefetched_objects_cache', None):
            instance._prefetched_objects_cache = {}

        return SuccessResponse("修改成功")


class getCatOptions(APIView):
    def get(self, request, *args, **kwargs):
        queryset = DataGenerationCat.objects.all()

        OptionsData = []
        for item in queryset:
            OptionsData.append(
                {
                    "label": item.name,
                    "value": item.id
                }
            )

        return SuccessResponse(OptionsData)


class DataArgsView(ModelViewSet):
    authentication_classes = []
    queryset = DataGeneration.objects.filter(isDelete=False).all()
    serializer_class = DataGenerationSer
    filter_class = DataGenerationFilter

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            logger.info(serializer.data)
            for item in serializer.data:
                item["creator"] = User.objects.get(id=item["creator"]).username
                item["modifier"] = User.objects.get(id=item["modifier"]).username
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)
        return SuccessResponse(serializer.data)

    # 获取单条数据
    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        queryset = instance.category.all()
        OptionsData = []
        for item in queryset:
            OptionsData.append(
                {
                    "label": item.name,
                    "value": item.id
                }
            )
        resultData = serializer.data
        resultData["category"] = OptionsData
        return Response(resultData)


# 新增数据类型
class postDataArgsView(APIView):
    @transaction.atomic
    def post(self, request, *args, **kwargs):
        setCreateUser(request)
        logger.info(request.data)
        ArgsData = {
            "name": request.data["name"],
            "value": request.data["value"],
            "index": request.data["index"],
            # "args": json.dumps(request.data["args"]),
            "args": request.data["args"],
            "description": request.data["description"],
            "isEnable": request.data["isEnable"],
            "isDownload": request.data["isDownload"],
            "isNoArgs": request.data["isNoArgs"],
            "creator": request.data["creator"],
            "modifier": request.data["modifier"],
        }
        instance = DataGeneration.objects.create(**ArgsData)
        cats = DataGenerationCat.objects.filter(id__in=request.data["category"])
        instance.category.set(cats)
        return SuccessResponse("操作成功")


# 编辑
class updateDataArgsView(APIView):
    @transaction.atomic
    def post(self, request, *args, **kwargs):
        logger.info(request.data)
        setModifyUser(request)
        instance = DataGeneration.objects.get(id=request.data["id"])
        instance.name = request.data["name"]
        instance.value = request.data["value"]
        instance.index = request.data["index"]
        instance.args = request.data["args"]
        instance.description = request.data["description"]
        instance.isEnable = request.data["isEnable"]
        instance.isDownload = request.data["isDownload"]
        instance.isNoArgs = request.data["isNoArgs"]
        instance.modifier = request.data["modifier"]
        instance.save()
        cats = DataGenerationCat.objects.filter(id__in=request.data["category"])
        instance.category.set(cats)

        return SuccessResponse("操作成功")


# 删除
class deleteDataArgsView(APIView):
    @transaction.atomic
    def post(self, request, *args, **kwargs):
        setModifyUser(request)
        instance = DataGeneration.objects.get(id=request.data["id"])
        instance.isDelete = True
        instance.modifier = request.data["modifier"]
        instance.save()

        return SuccessResponse("操作成功")


# 更改是否可用
class updateDataArgsIsEnableView(APIView):
    @transaction.atomic
    def post(self, request, *args, **kwargs):
        setModifyUser(request)
        instance = DataGeneration.objects.get(id=request.data["id"])
        instance.isEnable = request.data["isEnable"]
        instance.modifier = request.data["modifier"]
        instance.save()

        return SuccessResponse("操作成功")


# 进入页面时，初始化，获取第一个
class getFirstDataArgId(APIView):
    def get(self, request):
        cats = DataGenerationCat.objects.all()
        for cat in cats:
            instances = cat.datageneration_set.filter(isDelete=False, isEnable=True).all()

            # instances = DataGeneration.objects.filter(isDelete=False, isEnable=True).all()
            if instances:
                for instance in instances:
                    # logger.info(instance.category.all())
                    if instance.category.all():
                        return SuccessResponse(instance.id)


# 获取分类数据类型
class getCatDataArgs(APIView):
    @transaction.atomic
    def post(self, request, *args, **kwargs):
        resultData = []
        cats = DataGenerationCat.objects.filter(name__contains=request.data["catName"]).all()
        for cat in cats:
            catData = {
                "name": cat.name,
                "dataArgs": []
            }
            # dataArgs = DataGeneration.objects.filter(isDelete=False, category__id=cat.id).all()
            dataArgs = cat.datageneration_set.filter(isDelete=False, isEnable=True,
                                                     name__contains=request.data["dataName"]).all()
            if dataArgs:
                for dataArg in dataArgs:
                    catData["dataArgs"].append({
                        "id": dataArg.id,
                        "name": dataArg.name,
                        "description": dataArg.description
                    })
            if catData["dataArgs"]:
                resultData.append(catData)
        return SuccessResponse(resultData)


# 获取生成的数据
# 字段不存在时，调用该函数
def doesntExist(a):
    return "1212"


class DataView(APIView):

    def get_data(self, requestData):
        Language = requestData["language"]
        field = requestData["field"]
        dataNumber = requestData["dataNumber"]
        args = requestData["args"]

        resultData = []
        genera = DataGenerationEr(Language=Language)
        for i in range(dataNumber):
            fun = getattr(genera, field, doesntExist)
            result = fun(args)
            resultData.append({"data": result})

        logger.info(resultData)
        return resultData

    def post(self, request, *args, **kwargs):
        logger.info(request.data)
        try:
            resultData = self.get_data(request.data)
        except  Exception as e:
            return ErrorResponse(msg="无响应数据", data=[])
        return SuccessResponse(resultData)
